package com.edison.interceptor;



import com.edison.democommon.exception.UnauthorizedException;
import com.edison.democommon.util.JWTUntil;
import com.edison.democommon.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author edison
 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    private final String SECRET = "secret_test";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new UnauthorizedException("token is require.");
        }
        // Remove "Bearer " prefix
        String token = authHeader.substring(7);

        if (!JWTUntil.validateToken(token)) {
            throw new UnauthorizedException("token is invalid");
        }

        return  true;
    }


}
